<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>贪吃蛇</title>
    <style>
        #can {
            background: Black;
            display: block;
            margin: auto;
            position: fixed;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            border-radius: 2px;
        }

        #start,
        #re {
            width: 56px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border-radius: 4px;
            margin: auto;
            position: fixed;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            background-color: #0c60ee;
            color: #ffffff;
            cursor: pointer;
        }

        #re {
            width: 66px;
            background-color: #ffffff;
            color: red;
            display: none;
            z-index: 99;
        }

        #score {
            color: red;
            padding: 10px;
        }
    </style>
</head>
<body>

<canvas id="can" width="400" height="400"></canvas>
<div id="start" onclick="start();">开 始</div>
<div id="re" onclick="location.reload();">你死了</div>
<div id="score">得分：0</div>

<script>
    function start() {
        document.getElementById("start").style.display = 'none';
        var sn = [42, 41],
            dz = 43,
            fx = 1,
            n, ctx = document.getElementById("can").getContext("2d");

        var score = 0;

        function draw(t, c) {
            ctx.fillStyle = c;
            ctx.fillRect(t % 20 * 20 + 1, ~~(t / 20) * 20 + 1, 18, 18);
        }

        document.onkeydown = function (e) {
            fx = sn[1] - sn[0] == (n = [-1, -20, 1, 20][(e || event).keyCode - 37] || fx) ? fx : n
        };
        !function () {
            sn.unshift(n = sn[0] + fx);
            if (sn.indexOf(n, 1) > 0 || n < 0 || n > 399 || fx == 1 && n % 20 == 0 || fx == -1 && n % 20 == 19) {
                document.getElementById("re").style.display = 'block';
                return;
            }
            draw(n, "Lime");
            if (n == dz) {
                while (sn.indexOf(dz = ~~(Math.random() * 400)) >= 0) ;
                draw(dz, "Yellow");
                document.getElementById("score").innerHTML = '得分：' + score;
                score++;
            } else
                draw(sn.pop(), "Black");
            setTimeout(arguments.callee, 130);
        }();
    }

</script>

</body>
</html>